﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Se.Framework.Common.Rules
{
    public class RuleEngine<T>
    {
        private readonly IList<Se.Framework.Common.Rules.Rule<T>> rules;

        public RuleEngine()
        {
            rules = new List<Se.Framework.Common.Rules.Rule<T>>();
        }

        public void RegisterRule<TIn>(Se.Framework.Common.Rules.Rule<TIn> rule)
            where TIn : T
        {
            try
            {
                rule.Initialize();
                rules.Add(new ConvertionRule<TIn, T>(rule));
            }
            catch (Exception ex)
            {
                rule.Info.HasError = true;
                rule.Info.UnexpectedError = ex.Message;
            }
        }

        public virtual IEnumerable<Se.Framework.Common.Rules.IRuleInfo> GetMatchesFor(T item)
        {
            foreach (var rule in rules)
            {
                if (rule.Match(item))
                {
                    yield return rule.Info;
                }
            }
        }
    }
}